package org.yi.web.sys;

import org.apache.commons.lang.StringUtils;
import org.yi.core.annotation.Action;
import org.yi.core.enums.ParamTypeEnum;
import org.yi.web.base.BaseController;
import org.yi.web.sys.entity.ParamEntity;

@Action(action="/admin/param")
public class ParamController extends BaseController{
	
	public void index() {
		setAttr("paramTypeMap", ParamTypeEnum.toMap());
		setAttr("list", ParamEntity.dao.getAll());
		render("list.html");
	}
	
	public void add() {
		setAttr("paramTypeList", ParamTypeEnum.values());
		render("add.html");
	}
	
	public void save() {
		ParamEntity param = getModel(ParamEntity.class);
		try {
			if(ParamEntity.dao.getByCode(param.getStr("code")) != null) {
				addError("文章 [" + param.getStr("name") + "] 已存在!");
				keepPara();
				render("add.html");
			} else {
				param.save();
				redirect("/admin/param");
			}
		} catch(Exception e) {
			addError("保存参数 [" + param.getStr("code") + "] 出错, " + e.getMessage());
			keepPara();
			render("add.html");
		}
	}
	
	public void edit() {
		setAttr("paramTypeList", ParamTypeEnum.values());
		String id = getPara("id");
		if(StringUtils.isNotBlank(id)) {
			setAttr("param", ParamEntity.dao.findById(id));
		}
		
		render("add.html");
	}
	

	public void doEdit() {
		ParamEntity block = getModel(ParamEntity.class);
		try {
			block.update();
			redirect("/admin/param");
		} catch(Exception e) {
			addError("编辑区块 [" + block.getStr("name") + "] 出错, " + e.getMessage());
			keepPara();
			render("add.html");
		}
	}
	
	public void delete() {
		String id = getPara("id");
		System.out.println(id);
		try {
			if(StringUtils.isNotBlank(id)) {
				String[] idArr = id.split(",");
				ParamEntity.dao.deleteById((Object[])idArr);
			}
		} catch (Exception e) {
			addError("删除 [" + id + "] 出错, " + e.getMessage());
			keepPara();
		} finally {
			redirect("/admin/param");
		}
	}
}
